import {
	replaceURl
} from './util.js';

/**
 *  获取相册权限
 */
export function wxSaveAuth() {
  return new Promise((resolve, reject) => {
      uni.getSetting({
          success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) {
                // 如果没有写入权限，则获取写入相册权限
            uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                    resolve()
                },
            fail(err) {
                reject(err)
                // 用户拒绝授权
                uni.showModal({
                    content: '检测到您没打开相册权限，是否去设置打开？',
                    confirmText: '确认',
                    cancelText: '取消',
                    success(res) {
                        if (res.confirm) {
                            uni.openSetting({
                                success: res => {}
                            })
                        }
                    }
                })
            }
                })
            } else {
                resolve()
            }
          },
          fail(e) {
              reject(e)
          }
      })
  })
}

/**
 * 多文件下载并且保存 
 * @param {Array} urls 网络图片数组
 */
export function downloadImgs(urls, type) {
	console.log("urls", urls, type)
	// #ifdef MP-ALIPAY
	uni.saveImageToPhotosAlbum({
	  filePath: urls[0],
	  // showActionSheet: true,
	  success: () => {
	    uni.showToast({
	    	title: '图片保存成功',
	    	icon: 'none',
	    });
	  },
	}); 
	return	
	// #endif
	
	
	uni.showLoading({
		title: '图片下载中',
		mask: true
	});
	const imageList = []; // 循环数组
	
	// #ifndef H5
	uni.getSetting({
		success(res) {
			if (!res.authSetting['scope.writePhotosAlbum']) {
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						for (let i = 0; i < urls.length; i++) {
							imageList.push(getTempPath(urls[i], type));
						}

					}
				})
				
			}
		},
		fail: function(err) {
			uni.showLoading({
				title: '权限获取失败',
				mask: true
			});
		}
	})
	// #endif 
	// #ifdef H5 
	for (let i = 0; i < urls.length; i++) {
		let newTime = Math.round(new Date() / 1000)
		imageList.push(downloadIamge(urls[i], newTime));
	}
	// #endif

	uni.hideLoading();
	const loadTask = [];
	let index = 0;

	while (index < imageList.length) {
		loadTask.push(new Promise((resolve, reject) => {
			// 将数据分割成多个promise数组
			Promise.all(imageList.slice(index, index += 8)).then(res => {
				resolve(res);
			}).catch(err => {
				reject(err);
			});
		}));
	} // Promise.all 所有图片下载完成后弹出


	Promise.all(loadTask).then(res => {
		uni.showToast({
			title: '图片已保存到相册',
			duration: 1000
		});
	}).catch(err => {
		uni.showToast({
			title: `操作失败`,
			icon: 'none',
			duration: 1000
		});
	});
}

/**
 *
 * @param {String} url 单张网络图片
 */
//下载内容,临时文件路径

export function getTempPath(url, type) { 
	let saveFun = function(temp, resolve, reject) {
		uni.chooseImage({
		    count: 1,
		    sourceType: ['camera'],
		    success: function (res) {
		        uni.saveImageToPhotosAlbum({
		        	filePath: temp,
		        	success: function(res) {
		        		return resolve(res);
		        	},
		        	fail: function(err) {
		        		reject(temp + JSON.stringify(err));
		        	}
		        });
		    }
		});
		
	};

	return new Promise((resolve, reject) => {
		if (type == 'tmp') {
			saveFun(url, resolve, reject);
		} else {
			uni.downloadFile({
				url: url,
				success: function(res) {
					var temp = res.tempFilePath;
					saveFun(temp, resolve, reject);
				},
				fail: function(err) {
					reject(url + JSON.stringify(err));
				}
			});
		}
	});

}


export function getTempPathH5(url, type) {
	// #ifdef H5
	url = replaceURl(url);
	// #endif  

	let saveFun = function(temp, resolve, reject) {
		uni.downloadFile({
			url: temp,
			success: (res) => {
				if (res.statusCode === 200) {
					var oA = document.createElement("a");
					oA.download = ''; // 设置下载的文件名，默认是'下载'
					oA.href = res.tempFilePath;
					document.body.appendChild(oA);
					oA.click();
					oA.remove(); // 下载之后把创建的元素删除


					return resolve(res);
				}
			},
			fail: function(err) {
				reject(temp + JSON.stringify(err));
			}
		});

	};

	return new Promise((resolve, reject) => {
		if (type == 'tmp') {
			saveFun(url, resolve, reject);
		} else {
			uni.downloadFile({
				url: url,
				success: function(res) {
					var temp = res.tempFilePath;
					saveFun(temp, resolve, reject);
				},
				fail: function(err) {
					reject(url + JSON.stringify(err));
				}
			});
		}
	});


}

export function downloadIamge(imgsrc, name) {
	const url = imgsrc
	 convertUrlToBase64(url).then((base64) => {
		const blob =  convertBase64UrlToBlob(base64)
		if (getBrowser() === 'IE' || getBrowser() === 'Edge') {
			window.navigator.msSaveBlob(blob, name)
		} else {
			const a = document.createElement('a')
			const body = document.querySelector('body')
			a.download = name || 'image'
			a.href = URL.createObjectURL(blob)
			a.style.display = 'none'
			body.appendChild(a)
			a.click()
			body.removeChild(a)
			window.URL.revokeObjectURL(a.href)
		}
	})
}

export function convertUrlToBase64(url) {
	return new Promise((resolve, reject) => {
		const img = new Image()
		img.crossOrigin = 'Anonymous'
		img.src = url
		img.onload = function() {
			const canvas = document.createElement('canvas')
			canvas.width = img.width
			canvas.height = img.height
			const ctx = canvas.getContext('2d')
			ctx.drawImage(img, 0, 0, img.width, img.height)
			const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
			const dataURL = canvas.toDataURL('image/' + ext)
			const base64 = {
				dataURL: dataURL,
				type: 'image/' + ext,
				ext: ext
			}
			resolve(base64)
		}
	})
}
export function convertBase64UrlToBlob(base64) {
	const parts = base64.dataURL.split('base64,')
	const contentType = parts[0].split(':')[1]
	const raw = window.atob(parts[1])
	const rawLength = raw.length
	const uInt8Array = new Uint8Array(rawLength)
	for (let i = 0; i < rawLength; i++) {
		uInt8Array[i] = raw.charCodeAt(i)
	}
	return new Blob([uInt8Array], {
		type: contentType
	})
}
// 用来判断浏览器，解决浏览器兼容性问题：
export function getBrowser () {
// #ifdef H5
const userAgent = navigator.userAgent
  if (userAgent.indexOf('OPR') > -1) {
    return 'Opera'
  }
  if (userAgent.indexOf('Firefox') > -1) {
    return 'FF'
  }
  if (userAgent.indexOf('Trident') > -1) {
    return 'IE'
  }
  if (userAgent.indexOf('Edge') > -1) {
    return 'Edge'
  }
  if (userAgent.indexOf('Chrome') > -1) {
    return 'Chrome'
  }
  if (userAgent.indexOf('Safari') > -1) {
    return 'Safari'
  }
// #endif
}